<?php
namespace common\components\curl;

use common\helpers\DateHelper;
use common\models\CurlLog;
use yii\helpers\Json;
use yii\httpclient\Client;
use yii\httpclient\Request;
use yii\httpclient\RequestEvent;

abstract class AbstractCurl
{
    //远程系统名 会记录到log
    protected $remoteName;

    //记录log的扩展字段
    protected $extension;

    /**
     * @var Client
     */
    protected $client;

    protected $url;

    /**
     * AbstractCurl constructor.
     */
    public function __construct()
    {
        $this->url    = $this->getBaseUrl();
        $this->client = new Client(['baseUrl' => $this->url]);
        $this->init();
    }

    /**
     * @param string $url
     */
    public function setUrl(string $url)
    {
        $this->url = $url;
    }

    /**
     * init
     */
    public function init()
    {
        $code = md5(uniqid());
        // Ensure signature generation based on final data set:
        $this->client->on(Request::EVENT_BEFORE_SEND, function (RequestEvent $event) use ($code) {
            $model               = new CurlLog();
            $model->code         = $code;
            $model->url          = $event->request->getFullUrl();
            $model->remote       = $this->remoteName;
            $model->request_data = Json::encode($event->request->getData());
            $model->extension    = Json::encode($this->extension);
            $model->request_time = time();
            $model->created_at   = DateHelper::getCurrentDateTime();
            $model->save(false);
        });

        // Normalize response data:
        $this->client->on(Request::EVENT_AFTER_SEND, function (RequestEvent $event) use ($code) {
            $response_time        = time();
            $model                = CurlLog::findOne(['code' => $code]);
            $model->response_data = Json::encode($event->response->getData());
            $model->response_time = $response_time;
            $model->updated_at    = DateHelper::getCurrentDateTime();
            $model->save(false);
        });
    }

    /**
     * @return mixed
     */
    abstract protected function getBaseUrl();
}